<template>
  <div class="order-management">
    <div class="page-header">
      <h1>订单管理</h1>
    </div>
    <!-- 标签页（买家/卖家切换） -->
    <el-card class="tabs-card mb-4">
      <el-tabs v-model="activeTab" class="mb-2" @tab-change="handleTabChange">
        <el-tab-pane label="我的买家订单" name="buyer"></el-tab-pane>
        <el-tab-pane label="我的卖家订单" name="seller"></el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 搜索框 -->
    <el-card class="search-card mb-4">
      <el-input
          v-model="searchKeyword"
          clearable
          placeholder="请输入订单编号或商品名称搜索"
          style="width: 300px;"
          @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </el-card>

    <!-- 订单表格 -->
    <el-card class="order-card">
      <el-table
          v-loading="loading"
          :data="orders"
          border
          style="width: 100%"
          @row-click="handleRowClick">
        <el-table-column align="center" label="商品名称" prop="productName"></el-table-column>
        <el-table-column align="center" label="商品图片">
          <template #default="scope">
            <el-image
                :preview-src-list="[scope.row.productImage]"
                :src="scope.row.productImage || '默认图片地址'"
                style="width: 60px; height: 60px; object-fit: cover;"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单编号" prop="orderSn"></el-table-column>
        <el-table-column align="center" label="总价" prop="totalAmount">
          <template #default="scope">
            <span class="text-red-500">¥{{ scope.row.totalAmount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createdAt"></el-table-column>
        <el-table-column align="center" label="支付方式" prop="payType">
          <template #default="scope">
            <span>{{ getPayTypeText(scope.row.payType) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="支付时间" prop="payAt"></el-table-column>
        <el-table-column align="center" label="收货人姓名" prop="consignee"></el-table-column>
        <el-table-column align="center" label="收货地址" prop="fullAddress"></el-table-column>
        <el-table-column align="center" label="联系方式" prop="phone">
          <template #default="scope">
            <span>{{ scope.row.phone || '未填写' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态" prop="status">
          <template #default="scope">
            <el-tag
                :type="getStatusType(scope.row.status)"
                effect="light"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 操作栏 -->
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <!-- 1. 买家订单操作 -->
            <div v-if="activeTab === 'buyer'" @click.stop>
              <!-- 待支付状态：显示「立即支付」「取消」 -->
              <el-button
                  v-if="scope.row.status === 1"
                  size="small"
                  type="primary"
                  @click="openPaymentModal(scope.row)"
              >
                立即支付
              </el-button>
              <el-button
                  v-if="scope.row.status === 1"
                  size="small"
                  style="margin-left: 8px"
                  type="danger"
                  @click="cancelOrder(scope.row)"
              >
                取消订单
              </el-button>
            </div>

            <!-- 2. 卖家订单操作 -->
            <div v-else-if="activeTab === 'seller'" @click.stop>
              <!-- 已经支付状态 -->
              <el-button
                  v-if="scope.row.status === 2"
                  size="small"
                  type="danger"
                  @click="cancelOrder(scope.row.id)"
              >
                取消订单
              </el-button>
              <!-- 已支付状态：显示「发货」 -->
              <el-button
                  v-if="scope.row.status === 2"
                  size="small"
                  style="margin-left: 8px"
                  type="success"
                  @click="openShipModal(scope.row)"
              >
                发货
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 买家：支付模态框 -->
    <el-dialog v-model="paymentModalVisible" :width="500" title="订单支付">
      <div v-if="selectedOrder" class="payment-details">
        <div class="mb-4">
          <p class="font-bold">订单信息</p>
          <p>订单编号: {{ selectedOrder.orderSn }}</p>
          <p>商品名称: {{ selectedOrder.productName }}</p>
        </div>
        <div class="mb-4">
          <p class="font-bold">收货信息</p>
          <p>收货人: {{ selectedOrder.consignee }}</p>
          <p>收货地址: {{ selectedOrder.fullAddress }}</p>
          <p>联系电话: {{ selectedOrder.phone || '未填写' }}</p>
        </div>
        <div class="mb-4">
          <p class="font-bold text-red-500 text-xl">支付金额: ¥{{ selectedOrder.totalAmount || 0 }}</p>
        </div>
        <div class="mb-4">
          <p class="font-bold">支付方式</p>
          <el-radio-group v-model="paymentMethod" class="mt-2">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="card">银行卡支付</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <el-button @click="paymentModalVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认支付</el-button>
      </template>
    </el-dialog>

    <!-- 卖家：发货模态框 -->
    <el-dialog v-model="shipModalVisible" :width="500" title="订单发货">
      <div v-if="selectedOrder" class="ship-details">
        <div class="mb-4">
          <p class="font-bold">订单信息</p>
          <p>订单编号: {{ selectedOrder.orderSn }}</p>
          <p>商品名称: {{ selectedOrder.productName }}</p>
          <p>收货人: {{ selectedOrder.consignee }}（{{ selectedOrder.phone || '未填写' }}）</p>
          <p>收货地址: {{ selectedOrder.fullAddress }}</p>
        </div>
        <div class="mb-4">
          <p class="font-bold">物流信息</p>
          <el-form :model="shipForm" class="mt-2" label-width="100px">
            <el-form-item label="物流公司" prop="logisticsCompany" required>
              <el-input v-model="shipForm.shippingCompany" placeholder="请输入物流公司（如：顺丰）"></el-input>
            </el-form-item>
            <el-form-item label="物流单号" prop="logisticsNo" required>
              <el-input v-model="shipForm.logisticsNo" placeholder="请输入物流单号"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="shipModalVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确认发货</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import http from "@/request/Http.js";
import router from "@/router/index.js";

// 处理行点击事件
const handleRowClick = (row) => {
  // 跳转到订单详情页，传递订单ID和当前角色
  router.push({
    name: 'OrderDetail',
    params: {id: row.id},
    query: {role: activeTab.value}
  });
};

// 1. 基础状态管理
const activeTab = ref('buyer'); // 当前角色：buyer=买家，seller=卖家
const loading = ref(false);
const orders = ref([]); // 订单列表数据

// 分页相关变量
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页条数
const total = ref(0); // 总条数

// 搜索相关变量
const searchKeyword = ref(''); // 搜索关键词

// 2. 买家支付相关
const paymentModalVisible = ref(false); // 支付模态框显示状态
const selectedOrder = ref(null); // 当前选中的订单（支付/发货共用）
const paymentMethod = ref('alipay'); // 默认支付方式

// 3. 卖家发货相关
let shipModalVisible = ref(false); // 发货模态框显示状态
const shipForm = reactive({ // 发货表单数据（物流公司+单号）
  logisticsCompany: '',
  logisticsNo: ''
});

// 4. 状态映射
const statusMap = {
  1: {text: '待支付', type: 'warning'},
  2: {text: '已支付', type: 'success'},
  3: {text: '已发货', type: 'primary'},
  4: {text: '已完成', type: 'success'},
  5: {text: '已取消', type: 'info'}
};

// 5. 支付方式映射
const payTypeMap = {
  'alipay': '支付宝',
  'wechat': '微信支付',
  'card': '银行卡支付'
};

// 6. 工具函数
const getStatusText = (status) => statusMap[status]?.text || '未知状态';
const getStatusType = (status) => statusMap[status]?.type || 'info';
const getPayTypeText = (payType) => payTypeMap[payType] || '未支付';

// 7. 核心方法：获取订单列表（已修正为GET参数拼接）
const fetchOrders = async () => {
  loading.value = true;
  try {
    const endpoint = activeTab.value === 'buyer' ? 'buyerList' : 'sellerList';

    // 构建查询参数数组
    const params = new URLSearchParams({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    });
    const response = await http.get(`/order/${endpoint}?${params.toString()}`);

    console.log(response)
    orders.value = response.data.records || []; // 处理空数据
    total.value = response.data.total || 0; // 设置总条数
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败，请重试');
    orders.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 8. 标签页切换：重新拉取对应角色的订单
const handleTabChange = () => {
  // 切换标签时重置分页和搜索条件
  currentPage.value = 1;
  searchKeyword.value = '';
  fetchOrders();
};

// 处理搜索
const handleSearch = () => {
  // 搜索时重置到第一页
  currentPage.value = 1;
  fetchOrders();
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  fetchOrders();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchOrders();
};

// 9. 买家：打开支付模态框
const openPaymentModal = (order) => {
  if (order.consignee === null) {
    ElMessage.warning("未选择收货地址")
    return
  }
  selectedOrder.value = {...order};
  paymentModalVisible.value = true;
};

// 10. 买家：确认支付
const confirmPayment = async () => {
  if (!selectedOrder.value) return ElMessage.warning('请选择订单');
  try {
    const response = await http.post('/order/pay', {
      orderId: selectedOrder.value.id,
      payType: paymentMethod.value
    });

    if (response.code === 200) {
      ElMessage.success('正在拉起支付接口！');
      paymentModalVisible.value = false;
      setTimeout(() => {
        // 支付成功后跳转到支付成功页面
        router.push({
          path: '/PaySuccess',
          query: {
            orderId: selectedOrder.value.id,
            orderSn: selectedOrder.value.orderSn,
            amount: `¥${selectedOrder.value.totalAmount}`,
            productName: selectedOrder.value.productName,
            productImage: selectedOrder.value.productImage,
            consignee: selectedOrder.value.consignee,
            phone: selectedOrder.value.phone,
            fullAddress: selectedOrder.value.fullAddress
          }
        })
      }, 1000)
    } else {
      ElMessage.error(`支付失败：${response.data.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('支付接口调用失败:', error);
    ElMessage.error('支付请求异常，请重试');
  }
};

// 11. 通用：取消订单（买家/卖家都可用）
const cancelOrder = (order) => {
  ElMessageBox.confirm(
      '确定要取消该订单吗？取消后无法恢复',
      '警告',
      {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => {
    try {
      const orderData = {
        id: order.id,
        productId: order.productId
      }
      const response = await http.post(`/order/cancel`, orderData);
      if (response.code === 200) {
        ElMessage.success('订单已取消');
        await fetchOrders(); // 取消后刷新订单列表
      } else {
        ElMessage.error(`取消失败：${response.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('取消订单接口调用失败:', error);
      ElMessage.error('取消请求异常，请重试');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 12. 卖家：打开发货模态框
const openShipModal = (order) => {
  selectedOrder.value = {...order};
  // 重置发货表单
  shipForm.shippingCompany = '';
  shipForm.logisticsNo = '';
  shipModalVisible = true;
};

// 13. 卖家：确认发货
const confirmShip = async () => {
  if (!selectedOrder.value) return ElMessage.warning('请选择订单');
  // 表单验证
  if (!shipForm.shippingCompany) return ElMessage.warning('请输入物流公司');
  if (!shipForm.logisticsNo) return ElMessage.warning('请输入物流单号');

  try {
    const response = await http.post('/order/ship', {
      orderId: selectedOrder.value.id,
      logisticsCompany: shipForm.shippingCompany,
      logisticsNo: shipForm.logisticsNo
    });
    if (response.success) {
      ElMessage.success('发货成功！');
      shipModalVisible.value = false;
      await fetchOrders();
    } else {
      ElMessage.error(`发货失败：${response.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('发货接口调用失败:', error);
    ElMessage.error('发货请求异常，请重试');
  }
};

// 14. 页面初始化：加载买家订单
onMounted(() => fetchOrders());
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.tabs-card, .order-card, .search-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  overflow: hidden;
}

.tabs-card, .search-card {
  margin-bottom: 16px;
  padding: 16px;
}

.search-card {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.payment-details, .ship-details {
  line-height: 1.8;
}

.font-bold {
  font-weight: bold;
  margin-bottom: 8px;
  display: inline-block;
}

.ship-details .el-form {
  margin-top: 8px;
}

.ship-details .el-form-item {
  margin-bottom: 16px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 16px;
  text-align: right;
}
</style>